package com.xatz.scanner

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import com.xatz.ksoap2_android.SoapEnvelope
import com.xatz.ksoap2_android.serialization.SoapObject
import com.xatz.ksoap2_android.serialization.SoapSerializationEnvelope
import com.xatz.ksoap2_android.transport.HttpTransportSE
import com.xatz.scanner.bean.DataTable
import com.xatz.scanner.databinding.FragmentExecutionPageBinding
import okio.IOException
import org.xmlpull.v1.XmlPullParserException
import timber.log.Timber
import java.math.BigDecimal

/**
 * author: tdq
 * date: 2021/7/20
 * description: 执行页
 */
class ExecutionPageFragment : Fragment(), View.OnClickListener {

    private lateinit var mBinding: FragmentExecutionPageBinding

    private val numRequestCode = 100
    private val billOrderRequestCode = 200

    private var billCode = ""

    private var mActivity: SalesActivity? = null


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentExecutionPageBinding.inflate(inflater, container, false)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mActivity = activity as SalesActivity
        mBinding.btnClose.setOnClickListener(this)
        mBinding.btnFinish.setOnClickListener(this)
        mBinding.tvNum.setOnClickListener(this)
        mBinding.tvBillNum.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btnClose -> requireActivity().finish()
            R.id.btnFinish -> {
                AlertDialog.Builder(requireContext()).setTitle("提示")
                    .setMessage("确定完成吗？")
                    .setPositiveButton("确定") { dialog, _ ->
                        dialog.dismiss()
                        Thread { scannerFinishHandle() }.start()
                    }
                    .setNegativeButton("取消") { dialog, _ ->
                        dialog.dismiss()
                    }.show()
            }
            R.id.tvBillNum -> startActivityForResult(
                Intent(
                    requireContext(),
                    BarCodeActivity::class.java
                ), billOrderRequestCode
            )
            R.id.tvNum -> startActivityForResult(
                Intent(
                    requireContext(),
                    BarCodeActivity::class.java
                ), numRequestCode
            )
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            numRequestCode -> {
                if (resultCode == Activity.RESULT_OK) {
                    val barCodeStr = data?.getStringExtra("numText")
                    if (barCodeStr?.isNotBlank() == true) {
                        setBarCodeShow(barCodeStr)
                        Thread {
                            mActivity?.scannerResultHandle(barCodeStr)
                        }.start()
                    }
                }
            }

            billOrderRequestCode -> {
                if (resultCode == Activity.RESULT_OK) {
                    val barCodeStr = data?.getStringExtra("numText")
                    if (barCodeStr?.isNotBlank() == true) {
                        mActivity?.getDataInfoOnNet(barCodeStr.uppercase())
                    }
                }
            }
        }
    }

    fun onScannerResult(data: DataTable?) {
        data?.run {
            billCode = C_DELIVERY
            requireActivity().runOnUiThread {
                mBinding.tvBillNum.text = C_DELIVERY
                mBinding.tvCalNum.text = C_PLATE_NUMBER
                mBinding.tvCalNumTwo.text = C_PZ
//                mBinding.tvWeight.text = N_PLAN_WGT
            }
        }
    }

    fun countResult(count: Int, countTotal: Double) {
        var rCount = 0
        var rCountTotal = 0.0
        if (count >= 0) {
            rCount = count
        }
        if (countTotal >= 0) {
            rCountTotal = countTotal
        }
        requireActivity().runOnUiThread {
            mBinding.tvCount.text = rCount.toString()
            mBinding.tvWeight.text = BigDecimal(rCountTotal).setScale(3, BigDecimal.ROUND_HALF_UP).toString()
        }
    }

    fun clearData() {
        mBinding.tvBillNum.text = ""
        mBinding.tvCalNum.text = ""
        mBinding.tvWeight.text = ""
        mBinding.tvNum.text = ""
        mBinding.tvCount.text = ""
        mBinding.tvCalNumTwo.text = ""
        billCode = ""
    }

    private fun scannerFinishHandle() {
        if (billCode.isNotBlank()) {
            val userName =
                requireContext().getSharedPreferences(Constant.configName, Context.MODE_PRIVATE)
                    .getString(Constant.userName, "").toString()
            val userAccount =
                requireContext().getSharedPreferences(Constant.configName, Context.MODE_PRIVATE)
                    .getString(Constant.userAccount, "").toString()
            val namespace = "http://tempuri.org/"
            val transUrl = "http://www.sxjbjt.com:9084/Service1.asmx"
            val method = "SaleOutCompleteCommon"
            //注意版本使用，这个需要跟后台询问或者从wsdl文档或者服务说明中查看
            val envolopeVersion = SoapEnvelope.VER11
            //可能是namspace+method拼接
            val soapAction = "http://tempuri.org/SaleOutCompleteCommon"
            val request = SoapObject(namespace, method)
            //参数一定注意要有序，尽管是addProperty（），不要当作HttpUrl可以使用LinkedHashMap封装
            request.addProperty("billcode", billCode)
            request.addProperty("userId", userAccount)
            // SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            val envelope = SoapSerializationEnvelope(envolopeVersion)
            envelope.setOutputSoapObject(request)
            envelope.dotNet = true
            val se = HttpTransportSE(transUrl)
            try {
                se.call(soapAction, envelope) //envolopeVersion为ver12第一个参数可以为空，必须接口支持ver12才行
                val response = envelope.bodyIn as SoapObject
                //response的处理需要根据返回的具体情况，基本都要进行下面一步
                Timber.e(response.toString())
                val responseSoapObject = response.getProperty("SaleOutCompleteCommonResult") as SoapObject
                val resultCode = responseSoapObject.getProperty("resultCode").toString()
                val resultMsg = responseSoapObject.getProperty("resultMsg").toString()
                if (resultCode == "0") {
                    requireActivity().runOnUiThread {
                        val activity = requireActivity() as SalesActivity
                        activity.clearData()
                        val dialog = CustomDialog(activity)
                        if (!dialog.isShowing) {
                            dialog.contextText = "检配完成！"
                            dialog.showDialog()
                        }
                    }
                } else {
                    requireActivity().runOnUiThread {
                        requireContext().toast(resultMsg)
                    }
                }

            } catch (e: IOException) {
                e.printStackTrace()
            } catch (e: XmlPullParserException) {
                e.printStackTrace()
            }
        }
    }

    fun setBarCodeShow(barCode: String) {
        requireActivity().runOnUiThread {
            mBinding.tvNum.text = barCode
        }
    }
}